<?php

/**
 * CommonConfigBehavior is a behavior for the application.
 * It loads additional config parameters that cannot be statically
 * written in config/main
 */
class CommonConfigBehavior extends CBehavior
{
    private $result = array();

    /**
     * Declares events and the event handler methods
     * See yii documentation on behavior
     */
    public function events()
    {
        return array_merge(parent::events(), array(
            'onBeginRequest' => 'beginRequest',
            'onException' => 'doException',
        ));
    }

    /**
     * Load configuration that cannot be put in config/main
     */
    public function beginRequest()
    {
        // return json for ajax request
        if (Yii::app()->request->isAjaxRequest)
            header('Content-type: application/json');
        // select language for session
        $this->doLanguage();
        // set application name
        if (!isset($this->owner->name)) $this->setName();

    }

    /**
     * Load configuration that cannot be put in config/main
     */
    public function doException($event)
    {
        if (Yii::app()->request->isAjaxRequest){
            if ($event instanceof CExceptionEvent) {
                $this->result['resultCd'] = '01';
                $this->result['msg'] = $event->exception->getMessage();
            } elseif ($event instanceof CErrorEvent) {
                $this->result['resultCd'] = '02';
                $this->result['msg'] = $event->message;

            }
            $event->handled = true;
            exit(CJSON::encode($this->result));
        }
    }

    /**
     * Do language for set and change language
     */
    private function doLanguage()
    {
        if (isset($_POST['LANG_CODE'])) {
            $this->owner->user->setState('LANG_CODE', $_POST['LANG_CODE']);
            // set name
            $this->setName();
            $this->result['resultCd'] = '00';
            $this->result['msg'] = '';
            exit(CJSON::encode($this->result));

        }
        if ($this->owner->user->getState('LANG_CODE'))
            $this->owner->language = $this->owner->user->getState('LANG_CODE');
        else
            $this->owner->language = 'vi';
    }

    /**
     * Set Name
     */
    private function setName()
    {
        $criteria = new CDbCriteria;
        $criteria->select = array("FN_QTC_MULTI_NAME(C.COMN_CODE_NAME,C.COMN_CODE_ENG_NAME,:LANG_CODE) AS comn_code_name");
        $criteria->condition = " USE_YN= 'Y' AND TYPE_CODE = 'WEB_INFOR' AND COMN_CODE = 'NAME' ";
        $criteria->alias = "C";
        $criteria->params = array(':LANG_CODE' => Yii::app()->language);

        $name = CCommon::model()->find($criteria);
        if ($name != null)
            $this->owner->name = $name->comn_code_name;
        else $this->owner->name = 'Website';
    }
}

?>